const cloud = require('wx-server-sdk');
require('dotenv').config();

cloud.init({ 
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

async function getSaoBeiStoreConfig(schoolCode, productId) {
	try {
		console.log("getSaoBeiStoreConfig 入参:", schoolCode, productId, typeof productId);
		// 查询数据库中配置表，匹配 school_code 和 product_id
		const queryCondition = {
			school_code: schoolCode, // 匹配 schoolCode
			product_id: productId, // 匹配 productId
			config_name: 'subOrderConfig', // 限制 config_name
		};
		console.log("数据库查询条件:", JSON.stringify(queryCondition));
		const res = await db
			.collection('config') // 数据库集合名
			.where(queryCondition)
			.get();
		console.log("数据库查询结果:", JSON.stringify(res));
		if (!res || !res.data || res.data.length === 0) {
			console.error('配置表中未找到匹配的数据', { schoolCode, productId, typeOfProductId: typeof productId });
			return null;
		}

		// 返回查询结果的 content 数组中的第一个配置项
		const content = res.data[0]?.content;
		console.log("查询到的content:", JSON.stringify(content));
		if (!content || content.length === 0) {
			console.error('配置内容为空', { schoolCode, productId, typeOfProductId: typeof productId });
			return null;
		}

		return content[0]; // 默认返回第一个配置项
	} catch (error) {
		console.error('查询配置表失败:', error.message, { schoolCode, productId, typeOfProductId: typeof productId });
		throw new Error('Failed to retrieve configuration');
	}
}

/**
 * 获取产品服务配置
 * @param {Object} param0 - { productId, schoolCode }
 * @returns {Object} - { code, data/message }
 */
async function getProductServiceConfig({ productId, schoolCode }) {
	if (!productId || !schoolCode) {
		return { code: 400, message: '参数缺失' };
	}
	try {
		// 查询 config 集合，config_name 为 productServiceConfig
		const configRes = await db.collection('config')
			.where({
				config_name: 'productServiceConfig',
				product_id: productId,
				school_code: schoolCode
			})
			.get();

		if (!configRes.data || configRes.data.length === 0) {
			console.log('未找到产品服务配置', { productId, schoolCode });
			return {
				code: 404,
				message: '未找到产品服务配置',
				data: null
			};
		}

		const config = configRes.data[0];

		return {
			code: 200,
			message: 'success',
			data: config.content
		};
	} catch (e) {
		return { code: 500, message: '数据库查询失败', error: e.message };
	}
}

/**
 * 通用配置获取函数
 * @param {Object} param0 - { configName, schoolCode, productId }
 * @returns {Object} - { code, message, data }
 */
async function getConfigByNameSchoolProduct({ configName, schoolCode, productId }) {
	try {
		// Build query conditions
		const queryCondition = {};

		if (configName) {
			queryCondition.config_name = configName;
		}

		if (schoolCode) {
			queryCondition.school_code = schoolCode;
		}

		if (productId) {
			queryCondition.product_id = productId;
		}

		// Query config records
		const configRes = await db.collection('config').where(queryCondition).get();

		if (!configRes.data || configRes.data.length === 0) {
			console.error("No matching config found", queryCondition);
			return {
				code: 404,
				message: 'No matching config found',
				data: null
			};
		}

		// 检查是否查询到多个配置
		if (configRes.data.length > 1) {
			console.error("Multiple configs found, expected only one", queryCondition);
			return {
				code: 400,
				message: 'Multiple configs found, expected only one',
				data: null
			};
		}

		// 返回唯一的配置
		return {
			code: 200,
			message: 'success',
			data: configRes.data[0]
		};

	} catch (error) {
		console.error('获取配置失败:', error);
		return {
			code: 500,
			message: 'Internal Server Error',
			data: {}
		};
	}
}

module.exports = {
	getSaoBeiStoreConfig,
	getProductServiceConfig,
	getConfigByNameSchoolProduct,
}